package com.ym9527.controller;

import com.ym9527.entity.ThankYou;
import com.ym9527.entity.User;
import com.ym9527.jpa.ThankYouJpa;
import com.ym9527.jpa.UseJpa;
import com.ym9527.utils.R;
import org.springframework.http.HttpRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;


@RestController
@RequestMapping("thank")
public class ThankYouController {

    @Resource
    ThankYouJpa thankYouJpa;

    @Resource
    UseJpa useJpa;

    /**
     * 这是添加感谢信
     * @return
     */
    @PostMapping("addthank")
    @Transactional()
    public R AddThank(HttpServletRequest request,@RequestBody ThankYou thankYou){

        Long userId=useJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();

        thankYou.setCreateId(userId);

        thankYouJpa.save(thankYou);

        return R.ok();


    }

    /**
     * 这是获取全部感谢信
     * @return
     */
    @GetMapping("getall")
    @Transactional()
    public R GetAll(HttpServletRequest request){


      List<ThankYou> thankY=thankYouJpa.findAll();

        thankY.forEach(item->{

            User user=useJpa.getById(item.getCreateId());
            item.setCreateUserName(user.getUserName());
        });

        Collections.reverse(thankY);

        return R.ok(thankY);
    }

    /**
     * 这是删除感谢信
     * @return
     */
    @DeleteMapping("deletethank")
    @Transactional()
    public R DeleteThank(HttpServletRequest request,@RequestBody ThankYou thankYou){

           User user=useJpa.findByUserName(request.getHeader("user").split("-")[0]);

           if(user.getUserName().equals("admin")){

               thankYouJpa.deleteById(thankYou.getId());
               return R.ok();
           }else{
               return R.error("当前只有管理员能够删除感谢信");
           }




    }






}
